package info.rongtong.utils;

import info.rongtong.domain.FileUpload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;

public class FileUploadTools {

	private FileUploadTools(){}
	
	/**
	 * 得到文件扩展名
	 * @param fileName
	 * @return
	 */
	public static String getFileExt(String fileName){
		return fileName.substring(fileName.lastIndexOf(".")+1);	
	}
	
	/**
	 * 得到随机生成的名字
	 * @param oldFileName
	 * @return
	 */
	public static String getNewFileName(String oldFileName){
		return UUID.randomUUID().toString()+"."+getFileExt(oldFileName);
	}
	
	/**
	 * 写入到硬盘
	 * @param path
	 * @param file
	 */
	public static void saveFile(String path,File file){
		InputStream  input =null;
		OutputStream out = null;
		try {
			input = new FileInputStream(file);
			out = new FileOutputStream(path);
			byte[] bytes  = new byte[1024];
			while(input.read(bytes)!=-1){
				out.write(bytes);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				out.close();
				input.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	/**
	 * 保存文件
	 * @param fileUpload
	 * @return
	 */
	public static String fileUploadFunction(FileUpload fileUpload){
		StringBuffer sf = new StringBuffer();
		for(int i=0;i<fileUpload.getMyFile().length;i++){
			String path1 = FileUploadTools.getNewFileName(fileUpload.getMyFileFileName()[i]);
			String realPath = ServletActionContext.getServletContext().getRealPath("/");
			String path= realPath+"images/"+path1;
			FileUploadTools.saveFile(path, fileUpload.getMyFile()[i]);
			sf.append(path1).append("?");
		}
		return sf.substring(0, sf.length()-1);
	}
}
